package com.citrinus.feedme.places;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.citrinus.feedme.App;
import com.citrinus.feedme.R;
import com.citrinus.feedme.listener.PlacesUpdateListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.gson.Gson;

public class PlacesHandler extends AsyncTask<LatLng, Void, HttpResponse> {

	private static final String TAG = PlacesHandler.class.getSimpleName();
	public static final int RADIUS_DISTANCE_DOWNLOAD = 3000; // download a 3 km radius
	public static final int RADIUS_DISTANCE_SHOW = 1760; // Show 1 mile = 1760 yards

	private final static String BASE_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
	private final static String KEY = "?key=AIzaSyC0FVNXUpBzuDVaZYdRrTOffWn9ClDezlY";
	private final static String SENSOR = "&sensor=true";
	private final static String RADIUS = "&radius=" + RADIUS_DISTANCE_DOWNLOAD; // 1600
																				// =
	// 1
	// mile
	private final static String TYPES = "&types=restaurant";
	private final static String LOCATION = "&location=";
	private PlacesUpdateListener listener;
	private boolean isOk;

	private String buildURL(LatLng position) {
		String loc = LOCATION + position.latitude + "," + position.longitude;
		return BASE_URL + KEY + SENSOR + RADIUS + TYPES + loc;
	}

	@Override
	protected HttpResponse doInBackground(LatLng... params) {

		String url = buildURL(params[0]);
		Log.d(TAG, url);
		HttpGet request = new HttpGet(url);

		try {
			HttpClient httpclient = new DefaultHttpClient();
			return httpclient.execute(request);
		} catch (Exception e) {
			isOk = false;
			e.printStackTrace();
		} 
		return null;

	}

	@Override
	protected void onPostExecute(HttpResponse response) {
		super.onPostExecute(response);

		try {
			String json = EntityUtils.toString(response.getEntity());
			Places places = new Gson().fromJson(json, Places.class);
			App.instance.getDb().addPlaces(places.getResults());
			isOk = true;
			if (places.getResults().isEmpty()) {
				Toast.makeText(App.instance, App.instance.getResources().getString(R.string.restaurant_list_empty), Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			isOk = false;
			e.printStackTrace();
		} 
		listener.onPlacesUpdate(isOk);
	}	

	public void setListener(PlacesUpdateListener listener) {
		this.listener = listener;
	}
}
